package com.xly.webclick.net;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import com.xly.webclick.MyApplication;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.*;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by xuleyuan on 2018/8/14
 */

public class RetrofitClient {
    private static Retrofit sRetrofit;
    private static final String BASE_URL = "http://192.168.0.117:8080/";

    private RetrofitClient() {
    }

    public static Retrofit getRetrofit() {
        return sRetrofit;
    }

    public synchronized static void install(Application applicaition) {
        if (sRetrofit == null) {
            sRetrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(getSSLClient().build())
                    .build();
        }
    }

    public static OkHttpClient.Builder getSSLClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.addInterceptor(new HeaderInterceptor(MyApplication.getInstance()));
            builder.addInterceptor(new LoggingInterceptor());
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static class HeaderInterceptor implements Interceptor {

        private int versionCode;

        HeaderInterceptor(MyApplication applicaition) {
            try {
                PackageInfo info = applicaition.getPackageManager().getPackageInfo(applicaition.getPackageName(), 0);
                versionCode = info.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            okhttp3.Request request = chain.request();

            String langeuage = Locale.getDefault().getLanguage();

            okhttp3.Request.Builder builder = request.newBuilder();

            builder.header("version", String.valueOf(versionCode));
            builder.header("devicename", Build.DEVICE);
            builder.header("model", Build.MODEL);
            builder.header("manufacturer", Build.MANUFACTURER);
            builder.header("os", Build.VERSION.RELEASE);

            if (!TextUtils.isEmpty(langeuage)) {
                builder.header("x-locale", langeuage);
            }

            return chain.proceed(builder.build());
        }
    }
}
